const express = require('express')
const Result = require('../models/Result')
const { login, findUser } = require('../services/user')
const { md5, decoded } = require('../utils')
const { PWD_SALT, PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')
const { body, validationResult } = require('express-validator')
const boom = require('boom')
const jwt = require('jsonwebtoken')
const Admin = require('../models/admin')
const User = require('../models/user')
const Banner = require('../models/banner')

const router = express.Router()

router.post(
  '/login',
  [
    body('username').isString().withMessage('用户名必须为字符'),
    body('password').isString().withMessage('密码必须为数字')
  ],
  function (req, res, next) {
    const username = req.body.username
    const password = req.body.password
    Admin.find({ username }, function (err, doc) {
      if (err) {
        res.json({
          status: '1',
          msg: '管理员不存在'
        })
      } else {
        const dataPassword = doc[0].password
        if (password === dataPassword) {
          const token = jwt.sign(
            { username },
            PRIVATE_KEY,
            { expiresIn: JWT_EXPIRED }
          )
          new Result({ token }, '登录成功').success(res)
        }
      }
    })
    // if (!err.isEmpty()) {
    //   const [{ msg }] = err.errors
    //   next(boom.badRequest(msg))
    // } else {
    //   let { username, password } = req.body
    //   password = md5(`${password}${PWD_SALT}`)

    //   login(username, password).then(user => {
    //     if (!user || user.length === 0) {
    //       new Result('登录失败').fail(res)
    //     } else {

    //       new Result({ token }, '登录成功').success(res)
    //     }
    //   })
    // }
  })

router.get('/info', function (req, res) {
  res.json({
    code: 0,
    msg: '用户信息查询成功',
    data: {
      id: 1,
      username: 'admin',
      nickname: 'admin',
      role: 'admin',
      avatar: 'https://www.youbaobao.xyz/mpvue-res/logo.jpg',
      roles: ['admin']
    }
  })
})


router.post('/getUserList', function (req, res, next) {
  User.find({}, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: '查询失败'
      })
    } else {
      res.json({
        code: 0,
        msg: '请求成功',
        data: {
          count: doc.length,
          list: doc
        }
      })
    }
  })
})

// getUserOrder
router.post('/getUserOrder', function (req, res, next) {
  const _id = req.body
  console.log(req.body)
  User.find({ _id }, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: '查询失败'
      })
    } else {
      res.json({
        code: 0,
        msg: '订单查询成功',
        data: {
          count: doc.length,
          list: doc
        }
      })
    }
  })
})

router.post('/setBannerImage', function (req, res, next) {
  let imgUrl = req.body.imgUrl
  console.log(imgUrl)
  Banner.find({}, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: '设置banner失败'
      })
    } else {
      console.log('doc', doc)
      if (imgUrl) {
        let params = {
          imgUrl: imgUrl
        }
        let newArray = doc.push({ imgUrl: imgUrl })
        console.log('newArray', newArray)
        Banner.insertMany(params, function (e, d) {
          if (e) {
            res.json({
              status: '1',
              msg: '设置banner失败'
            })
          } else {
            res.json({
              code: 0,
              msg: '设置banner成功',
              data: {
                count: doc.length,
                list: doc
              }
            })
          }
        })
      }
    }
  })
})

module.exports = router
